//协议容器
var proto_select_option = []
//文件类型容器
var filetype_select_option = []
//请求用
var playback_config_request = {};
//表格用
var tablelist = []
//表格类型选择总容器
var all_select_option = []

$.ajax({
	url: 'http://' + ipm + ':8081/dict/query',
	type: 'POST',
	contentType: 'application/json',
	dataType: 'json',
	data: {},
	success: function (response) {
		proto_select_option = []
		filetype_select_option = []
		tablelist = []
		console.log(response);
		playbackConfigRead(response)
		console.log(tablelist)
		var dm8data = response.data;
		var dm8content = dm8data.content;
		var datalist = [];
		var testa;
		var testb;
		for (var i = 0; i < dm8content.length; i++) {
			if (dm8content[i].cfgType == 4) {
				datalist[i] = dm8content[i].content;
				testa = JSON.parse(datalist[i]);
				testb = testa.protocols;
				for (var j = 0; j < testb.length; j++) {
					proto_name = "协议-" + testb[j].name
					proto_select_option.push(proto_name)
					selectObj = {
						value: "",
						text: ""
					}
					selectObj.value = proto_name
					selectObj.text = proto_name
					all_select_option.push(selectObj)
				}
			}
			if (dm8content[i].cfgType == 6) {
				datalist[i] = dm8content[i].content;
				testa = JSON.parse(datalist[i]);
				testb = testa.type_defines;
				for (var j = 0; j < testb.length; j++) {
					filetype_select_option.push(testb[j])
					selectObj = {
						value: "",
						text: ""
					}
					selectObj.value = testb[j]
					selectObj.text = testb[j]
					all_select_option.push(selectObj)
				}
			}
		}
		console.log(all_select_option)
		var data_type = document.getElementById("data_type")
		for (var i = 0; i < proto_select_option.length; i++) {
			data_type.options.add(new Option(proto_select_option[i], proto_select_option[i]));
		}
		for (var i = 0; i < filetype_select_option.length; i++) {
			data_type.options.add(new Option(filetype_select_option[i], filetype_select_option[i]));
		}
		bootstrapTable_init();
	}
});


var field
layui.use('form', function () {
	var form = layui.form;
	//方法提交
	$('#testSubmitBtn').on('click', function (data) {
		form.submit('playbackfield', function (data) { // 注：v2.7.0 新增
			// 回调函数返回结果跟上述 submit 事件完全一致
			field = data.field;
			//console.log(data.field)
			// do something
			// if (field.space == "数据库") {
			// 	document.getElementById("space").disabled = false;
			// 	console.log("11")
			// }
			saveConfig();
			// if (field.space == "数据库") {
			// 	document.getElementById("space").disabled = true;
			// 	console.log("22")

			// }
		});
		return false;
	});

	// //空间框事件
	// form.on('select(data_type)', function (data) {
	// 	console.log(data.value);
	// 	if (data.value.includes('协议-')) {
	// 		document.getElementById("space").selectedIndex = "数据库"
	// 		document.getElementById("space").value = "数据库"
	// 		document.getElementById("space").disabled = true;
	// 	} else {
	// 		document.getElementById("space").disabled = false;
	// 	}
	// 	form.render('select');
	// });
});

//保存配置
function saveConfig() {
	var arrPlaybCfg = playback_config_request.remote;
	var id = playback_config_request.max_id;
	id++;
	var playbCfgWeb = {
		"cfgType": "8",
		"cfgName": "replay.json",
		"content": ""
	}
	var playbCfgSave = {
		"cfg_type": 8,
		"max_id": "",
		"remote": [],
		"local": []
	}
	if (id) {
		playbCfg = {
			"id": 1,
			"sensor_id": 0,
			"data_id": 1,
			"data_type": "点迹x",
			"space": "空间1",
			"data_path": "/dj-x",
			"is_protocol": true
		}
		playbCfg.id = id;
	} else {
		arrPlaybCfg = []
		playbCfg = {
			"id": 2,
			"sensor_id": 0,
			"data_id": 2,
			"data_type": "点迹c",
			"space": "空间1",
			"data_path": "/dj-c",
			"is_protocol": true
		}
		id = 0;
		playbCfg.id = 0;
	}
	console.log(field);
	playbCfg.sensor_id = parseInt(field.sensor_id);
	playbCfg.data_id = parseInt(field.data_id);
	if (field.data_type.includes('协议-')) {
		data_type_save = field.data_type.substring(3)
		playbCfg.is_protocol = true;
	} else {
		data_type_save = field.data_type
		playbCfg.is_protocol = false;
	}
	playbCfg.data_type = data_type_save;
	playbCfg.space = field.space;
	playbCfg.data_path = field.data_path;
	// if (field.space == "数据库" && field.data_type.includes('协议-')) {
	// 	console.log("11");
	// 	playbCfg.is_protocol = true;
	// } else {
	// 	playbCfg.is_protocol = false;
	// }
	arrPlaybCfg.push(playbCfg);
	playbCfgSave.remote = arrPlaybCfg;
	playbCfgSave.local = playback_config_request.local;
	playbCfgSave.max_id = id;
	playbCfgWeb.content = JSON.stringify(playbCfgSave);
	console.log(playbCfgSave);
	postQuestSave(playbCfgWeb);
	layer.msg('新增成功', { icon: 1 });
	// window.location.reload();
	//等待读取
	for (var i = 0; i < 10; i++) {
		if (i == 9) {
			$.ajax({
				url: 'http://' + ipm + ':8081/dict/query',
				type: 'POST',
				contentType: 'application/json',
				dataType: 'json',
				data: {},
				success: function (response) {
					tablelist = []
					playbackConfigRead(response)
					bootstrapTable_init();
				}
			});
		} else {
			// alert('加载失败，请刷新重试')
			console.log("loading")
		}
	}
}


function bootstrapTable_init() {
	$("#bootstrap-table").bootstrapTable('destroy').bootstrapTable({
		data: tablelist,
		dataType: 'json',
		pagination: true,                   //是否显示分页（*）
		cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
		sortOrder: "asc",                   //排序方式
		sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
		pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
		pageSize: 10,                     //每页的记录行数（*）
		pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
		strictSearch: true,
		minimumCountColumns: 1,             //最少允许的列数
		uniqueId: "id",                     //每一行的唯一标识，一般为主键列
		onEditableSave: onEditableSave,
		columns: [
			{
				field: 'ID',
				align: 'center',
				title: '序号',
				width: 60,
				formatter: function (value, row, index) {
					return index + 1;
				}
			}, {
				field: 'sensor_id',
				align: 'center',
				title: '传感器号',
				width: 80,
				editable: true
			}, {
				field: 'data_id',
				align: 'center',
				title: '数据编号',
				width: 80,
				editable: true
			}, {
				field: 'data_type',
				align: 'center',
				title: '数据类型',
				// formatter: function (value, row, index) {
				// 	return "<div><select onchange='selectChange(this," + index + ")' name='suffix_two" + index + "' id='suffix_two" + index + "' class='form-control'></select></div>";
				// }
				editable: {
					type: 'select',
					title: '值类型',
					source: all_select_option
				}
			}, {
				field: 'space',
				align: 'center',
				title: '数据空间',
				// formatter: function (value, row, index) {
				// 	return "<div><select name='space" + index + "' id='space" + index + "' class='form-control' ><option value='空间1'>空间1</option><option value='空间2'>空间2</option><option value='数据库'>数据库</option></select></div>";
				// }
				editable: {
					type: 'select',
					title: '值类型',
					source: [{
						value: "空间1",
						text: "空间1"
					}, {
						value: "空间2",
						text: "空间2"
					}
						// , {
						// 	value: "数据库",
						// 	text: "数据库"
						// }
					]
				}
			}, {
				field: 'data_path',
				align: 'center',
				title: '数据目录',
				editable: true
			}, {
				field: 'id',
				align: 'center',
				title: '删除',
				formatter: function (value, row, index) {
					// return "<a href='javascript:;' class='btn btn-xs red' onclick=\"deleteRow('" + value + "','" + index + "')\" title='删除'><span class='feather-trash-2'></span></a>";
					var id = value;
					//var name = row[index].name;
					//console.log(name);
					var result = "";
					result += "<a href='javascript:;' class='btn btn-xs red' onclick=\"playback_config_modify(" + id + ")\" title='删除'><span class='feather-trash-2'></span></a>";

					return result;
				}
			}
		]
	});
}


//删除协议字段解析表JSON
function playback_config_modify(args) {

	console.log(args)
	var arrPlaybCfg = playback_config_request.remote;
	for (var i = 0; i < arrPlaybCfg.length; i++) {
		if (arrPlaybCfg[i].id == args) {
			arrPlaybCfg.splice(i, 1);
			console.log(arrPlaybCfg)

		}
	}
	var playbCfgWeb = {
		"cfgType": "8",
		"cfgName": "replay.json",
		"content": ""
	}

	var playbCfgSave = {
		"cfg_type": 8,
		"max_id": "",
		"remote": [],
		"local": []
	}
	playbCfgSave.remote = arrPlaybCfg;
	playbCfgSave.local = playback_config_request.local;
	playbCfgSave.max_id = playback_config_request.max_id;
	playbCfgWeb.content = JSON.stringify(playbCfgSave);
	console.log(playbCfgSave);
	postQuestSave(playbCfgWeb);
	window.location.reload();
}


//编辑保存
function onEditableSave(field, row, rowIndex, oldValue, $el) {
	//alert("字段名：" + field + "，当前值：" + row[field] + "，旧值：" + oldValue + "，顺位：" + rowIndex);
	var data = $("#bootstrap-table").bootstrapTable('getData');
	var objChange = data[rowIndex];
	var idChange = objChange.id;
	console.log(objChange.method)

	var arr = playback_config_request.remote;
	var playbCfgWeb = {
		"cfgType": "8",
		"cfgName": "replay.json",
		"content": ""
	}
	var playbCfgSave = {
		"cfg_type": 8,
		"max_id": "",
		"remote": [],
		"local": []
	}
	if (field == "sensor_id") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].sensor_id = row[field];
			}
		}
		playbCfgSave.remote = arr;
		playbCfgSave.local = playback_config_request.local;
		playbCfgSave.max_id = playback_config_request.max_id;
		playbCfgWeb.content = JSON.stringify(playbCfgSave)
		postQuestSave(playbCfgWeb);
		console.log(playbCfgWeb)
		layer.msg('修改成功', { icon: 1 });
	} else if (field == "data_id") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].data_id = row[field];
			}
		}
		playbCfgSave.remote = arr;
		playbCfgSave.local = playback_config_request.local;
		playbCfgSave.max_id = playback_config_request.max_id;
		playbCfgWeb.content = JSON.stringify(playbCfgSave)
		postQuestSave(playbCfgWeb);
		console.log(playbCfgWeb)
		layer.msg('修改成功', { icon: 1 });
	} else if (field == "data_type") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				// arr[i].data_type = row[field];
				if (row[field].includes("协议-")) {
					arr[i].data_type = row[field].substring(3);
					arr[i].is_protocol = true;
					// arr[i].space = "数据库";
				} else {
					arr[i].data_type = row[field];
					arr[i].is_protocol = false;
				}
			}
		}
		playbCfgSave.remote = arr;
		playbCfgSave.local = playback_config_request.local;
		playbCfgSave.max_id = playback_config_request.max_id;
		playbCfgWeb.content = JSON.stringify(playbCfgSave)
		postQuestSave(playbCfgWeb);
		bootstrapTable_init()
		console.log(playbCfgWeb)
		layer.msg('修改成功', { icon: 1 });
	} else if (field == "space") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].space = row[field];
				// if (objChange.data_type.includes("协议-")) {
				// 	alert("协议类仅可为数据库");
				// 	window.location.reload();
				// 	// bootstrapTable_init()
				// 	return false
				// } else {
				// 	arr[i].space = row[field];
				// }
			}
		}
		playbCfgSave.remote = arr;
		playbCfgSave.local = playback_config_request.local;
		playbCfgSave.max_id = playback_config_request.max_id;
		playbCfgWeb.content = JSON.stringify(playbCfgSave)
		postQuestSave(playbCfgWeb);
		console.log(playbCfgWeb)
		layer.msg('修改成功', { icon: 1 });
	} else if (field == "data_path") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].data_path = row[field];
			}
		}
		playbCfgSave.remote = arr;
		playbCfgSave.local = playback_config_request.local;
		playbCfgSave.max_id = playback_config_request.max_id;
		playbCfgWeb.content = JSON.stringify(playbCfgSave)
		postQuestSave(playbCfgWeb);
		console.log(playbCfgWeb)
		layer.msg('修改成功', { icon: 1 });
	}
}

// $(function () {
// 	bootstrapTable_init()
// });
